package com.dictionary.service.impl;

import com.dictionary.mapper.WordMapper;
import com.dictionary.pojo.Result;
import com.dictionary.pojo.Word;
import com.dictionary.service.WordService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Classname WordServiceImpl
 * @Description TODO
 * @Date 2025/5/15 21:14
 * @Created by xxx
 */
@Slf4j
@Service
public class WordServiceImpl implements WordService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private WordMapper wordMapper;

    @Value("${word-api.base-url}")
    private String baseUrl;

    @Value("${word-api.word-list-path}")
    private String wordListPath;

    @Override
    public Result getWord(Word word) {
        String queryUrl = baseUrl + "?word=" + word.getWord();
        String jsonStr = restTemplate.getForObject(queryUrl, String.class);
        try {
            log.info("查询结果：{}", jsonStr);
            return Result.success(parseJsonToWord(jsonStr));
        } catch (Exception e) {
            log.error("查询失败：{}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }


    @Override
    public List<Word> getWordList() {
        log.info("获取单词列表");
        try {
            List<Word> wordList = wordMapper.selectAll();
            log.info("获取到 {} 个单词", wordList.size());
            return wordList;
        } catch (Exception e) {
            log.error("获取单词列表失败: {}", e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public Word getWordDetail(String word) {
        log.info("获取单词详情: {}", word);
        try {
            Word wordDetail = wordMapper.selectByWord(word);
            if (wordDetail != null) {
                log.info("获取到单词详情: {}", word);
            } else {
                log.warn("单词不存在: {}", word);
            }
            return wordDetail;
        } catch (Exception e) {
            log.error("获取单词详情失败: {}", e.getMessage(), e);
            throw e;
        }
    }

    private Word parseJsonToWord(String jsonStr) throws Exception {
        JsonNode rootNode = objectMapper.readTree(jsonStr);
        JsonNode dataNode = rootNode.get("data");
        int code = rootNode.get("code").asInt();
        if (code != 200) {
            String message = rootNode.get("msg").asText();
            throw new Exception(message);
        }

        Word.WordDetail.WordDetailBuilder detailBuilder = Word.WordDetail.builder();
        Word word = Word.builder()
                .word(dataNode.path("word").asText())
                .ukPhonetic(dataNode.path("ukphone").asText())
                .usPhonetic(dataNode.path("usphone").asText())
                .ukAudioUrl(dataNode.path("ukspeech").asText())
                .usAudioUrl(dataNode.path("usspeech").asText())
                .bookId(dataNode.path("bookId").asText())
                .build();

        // 翻译 translations
        if (dataNode.hasNonNull("translations")) {
            for (JsonNode t : dataNode.get("translations")) {
                String pos = t.path("pos").asText();
                String chinese = t.path("tran_cn").asText();
                word.addDetail(detailBuilder
                        .type("TRANSLATION")
                        .pos(pos)
                        .chinese(chinese)
                        .build());
            }
        }

        // 派生词 relWords
        if (dataNode.hasNonNull("relWords")) {
            for (JsonNode rw : dataNode.get("relWords")) {
                String pos = rw.path("Pos").asText();
                if (rw.hasNonNull("Hwds") && rw.get("Hwds").isArray()) {
                    for (JsonNode hwd : rw.get("Hwds")) {
                        String relatedWord = hwd.path("word").asText();
                        word.addDetail(detailBuilder
                                .type("RELATED_WORD")
                                .pos(pos)
                                .english(relatedWord)
                                .build());
                    }
                }
            }
        }

        // 短语 phrases
        if (dataNode.hasNonNull("phrases")) {
            for (JsonNode p : dataNode.get("phrases")) {
                String phraseEn = p.path("p_content").asText();
                String phraseCn = p.path("p_cn").asText();
                word.addDetail(detailBuilder
                        .type("PHRASE")
                        .english(phraseEn)
                        .chinese(phraseCn)
                        .build());
            }
        }

        // 例句 sentences
        if (dataNode.hasNonNull("sentences")) {
            for (JsonNode s : dataNode.get("sentences")) {
                String sentenceEn = s.path("s_content").asText();
                String sentenceCn = s.path("s_cn").asText();
                word.addDetail(detailBuilder
                        .type("EXAMPLE_SENTENCE")
                        .english(sentenceEn)
                        .chinese(sentenceCn)
                        .build());
            }
        }

        return word;
    }
}
